import sharp from 'sharp';
import { Context } from 'koishi'

export function formatDate(date: Date): string {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份是从0开始的，所以要加1
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');
  
    return `${year}年${month}月${day}日 ${hours}:${minutes}:${seconds}`;
}

export async function resizeImageToBase64(ctx: Context, url: string): Promise<string> {
    // 使用 ctx.http.get 获取图片 Buffer
    const arrayBuffer = await ctx.http.get<ArrayBuffer>(url, {
      responseType: 'arraybuffer',
    })
  
    const inputBuffer = Buffer.from(arrayBuffer)
  
    // 获取原始图像尺寸
    const metadata = await sharp(inputBuffer).metadata()
    const { width, height } = metadata
  
    if (!width || !height) {
      throw new Error('无法获取图像尺寸')
    }
  
    const maxSize = 32
    const scale = maxSize / Math.max(width, height)
  
    // 处理图像
    const resizedBuffer = await sharp(inputBuffer)
      .resize({
        width: Math.round(width * scale),
        height: Math.round(height * scale),
      })
      .png()
      .toBuffer()
  
    // 转换为 base64
    return `data:image/png;base64,${resizedBuffer.toString('base64')}`
  }